package com.kaluli.project.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.kaluli.project.domain.entity.AbroadVO;
import com.kaluli.project.domain.entity.KllOrderDataVo;
import com.kaluli.project.domain.entity.KllUserDataVo;
import com.kaluli.project.utils.DateUtil;

/**
 * @author niwei
 */
@Service
@Configuration
@Transactional
@PropertySource({ "classpath:mail.properties" })
public class SimpleOrdersheetService {
	
	@Autowired
	private Environment env;

    private static final String[] titles = {
            "所属仓库", "订单单号", "下单支付时间","揽收时间", "签收时间","发货时间", "快递时间"};

    private static final String[] CUSTOM = {"上海仓","南沙保税仓","深圳批发仓","宁波保税仓"};// 1,15,10
    
    private List<KllOrderDataVo> shanghai = new ArrayList<>();
    
    private List<KllOrderDataVo> hangkong = new ArrayList<>();
    
    private List<KllOrderDataVo> shenzhen = new ArrayList<>();
    
    private List<KllOrderDataVo> ningbo = new ArrayList<>();
    
    private List<KllOrderDataVo> nansha  = new ArrayList<>();
    
    
    
    public List<KllOrderDataVo> repList(List<KllOrderDataVo> list){
    	
    	for(KllOrderDataVo vo:list){
    		
    		String content = vo.getContent();
    		String orderTime = vo.getOrder_time();
    		List<AbroadVO> volist = new ArrayList<>();
	    	if(content.contains("}]")){
	    		volist = JSON.parseArray(content, AbroadVO.class);
	    	}else{
	    		continue;
	    	}
	    	AbroadVO first = volist.get(0);
	    	AbroadVO last = volist.get(volist.size()-1);
	    	
	    	System.out.println("时间段="+first.getTime()+"----"+last.getTime());
	    	/*
	    	String endTime ="";
	    	String startTime = "";
	    	int index =1;
	    	for(AbroadVO o : volist){
	    		if(o.getStatus().equals("\u7b7e\u6536")){
	    			endTime = o.getTime();
	    			vo.setEnd_time(endTime);
	    			continue;
	    		}
	    		if(o.getStatus().equals("揽收")){
	    			if(index ==1){
	    				startTime = o.getTime();
		    			vo.setStart_time(startTime);
	    			}
	    			index++;
	    			
	    		}
	    	}*/
	    	
	    	String endTime =first.getTime();
	    	String startTime = last.getTime();
	    	String time = "";
	    	Date start = DateUtil.str2Date(startTime, "yyyy-MM-dd HH:mm:ss");
	    	Date end = DateUtil.str2Date(endTime, "yyyy-MM-dd HH:mm:ss");
	    	if(end.after(start)){
	    		vo.setStart_time(startTime);
		    	vo.setEnd_time(endTime);
	    	}else{
	    		vo.setStart_time(endTime);
		    	vo.setEnd_time(startTime);
		    	time = endTime;
		    	endTime = startTime;
		    	startTime = time;
	    	}
	    	
	    	
	    	
	    	if(StringUtils.isNotBlank(endTime) && StringUtils.isNotBlank(startTime)){
	    		Date startDate = DateUtil.str2Date(startTime,null);
	    		Date endDate = DateUtil.str2Date(endTime, null);
	    		Date orderDate1 = DateUtil.str2Date(orderTime, null);
	    		Date orderDate2 = DateUtil.str2Date(orderTime, null);
	    		//收货时间
//	    		int delivHour = DateUtil.intervalHours(orderDate1,startDate);
	    		long delivHour =Math.abs(startDate.getTime()-orderDate2.getTime());
	    		long result1 = delivHour/(1000*60*60);
	    		//收货时间
	    		BigDecimal deliv = new BigDecimal(result1);
	    		BigDecimal num = new BigDecimal(Double.valueOf("24"));
	    		BigDecimal delivery = deliv.divide(num,2,BigDecimal.ROUND_UP);
	    		
//	    		int expressHour = DateUtil.intervalHours(orderDate2,endDate);
	    		long expressHour =Math.abs(endDate.getTime()-orderDate2.getTime());
	    		long result2 = expressHour/(1000*60*60);
	    		BigDecimal expre = new BigDecimal(result2);
	    		BigDecimal express = expre.divide(num,2,BigDecimal.ROUND_UP);
	    		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//	    		System.out.println("order="+vo.getOrder_number()+"==start="+orderTime+"==end="+endTime+"  express="+express.toString());
//	    		System.out.println("startTime="+startTime+"----"+sf.format(orderDate1));
	    		System.out.println(sf.format(startDate));
	    		System.out.println(sf.format(endDate));
	    		
	    		vo.setDeliv_time(delivery.toString());
	    		vo.setExpr_time(express.toString());
	    		
	    	}else{
	    		continue;
	    	}
	    	String type = vo.getDepot_type();
    		/*String time = vo.getExpr_time();
    		String deliv = vo.getDeliv_time();
    		int i = time.indexOf(".");
    		int j = deliv.indexOf(">");
    		time = time.substring(0, i+3);
    		vo.setExpr_time(time);
    		vo.setDeliv_time(deliv.substring(0,j+3));*/
    		if(StringUtils.isNotBlank(type)){
    			if(type.equals("1")){
    				vo.setDepot_type(CUSTOM[0]);
    				shanghai.add(vo);
    			}else if(type.equals("10")){
    				vo.setDepot_type(CUSTOM[1]);
    				nansha.add(vo);
    			}else if(type.equals("19")){
    				vo.setDepot_type(CUSTOM[3]);
    				ningbo.add(vo);
    			}else if(type.equals("23")){
    				vo.setDepot_type(CUSTOM[2]);
    				shenzhen.add(vo);
    			}
    		}
    	}
    	
    	return list;
    	 
    }

    public void sendEmailByTime(List<KllOrderDataVo> list) throws Exception {
    	
    	list = repList(list);
        Workbook wb = new HSSFWorkbook();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());

        fillSheet(shanghai, wb, "上海仓");
        fillSheet(shenzhen, wb, "深圳批发仓");
        fillSheet(ningbo, wb, "宁波保税仓");
        fillSheet(nansha, wb, "南沙保税仓");
        
        // Write the output to a file
        String file = "订单物流信息报表_"+date+".xls";
        FileOutputStream out = new FileOutputStream(file);
        wb.write(out);
        out.close();
        
        sendMail(file);
        
        // 删除临时文件
		File dayReportFile = new File(file);
		dayReportFile.delete();
    }
    
    public void fillSheet(List<KllOrderDataVo> list,Workbook wb,String name){
    	Sheet sheet = wb.createSheet(name);

        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(12.75f);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
        //获取要导出的数据
        Row row;
        Cell cell;
        int rownum = 1;
        
       
        for(int m=0;m<list.size();m++,rownum++){
        	 row = sheet.createRow(rownum);
        	 KllOrderDataVo vo =list.get(m);
        	 cell = row.createCell(0);
             cell.setCellValue(vo.getDepot_type());
             cell = row.createCell(1);
             cell.setCellValue(vo.getOrder_number());
             cell = row.createCell(2);
             cell.setCellValue(vo.getOrder_time());
             cell = row.createCell(3);
             cell.setCellValue(vo.getStart_time());
             cell = row.createCell(4);
             cell.setCellValue(vo.getEnd_time());
             cell = row.createCell(5);
             cell.setCellValue(vo.getDeliv_time());
             cell = row.createCell(6);
             cell.setCellValue(vo.getExpr_time());
        }
    }
    
    /**
	 * 发送
	 * 
	 * @param propMap
	 * @param dayReportName
	 * @throws MessagingException
	 * @throws IOException
	 */
	private  void sendMail(String dayReportName) throws MessagingException, IOException {
		 Properties props = new Properties();  
	        // 开启debug调试  
	        props.setProperty("mail.debug", "false");  
	        // 发送服务器需要身份验证  
	        props.setProperty("mail.smtp.auth", "true");  
	        // 设置邮件服务器主机名  
	        props.setProperty("mail.host", env.getProperty("nsapi.mail.smtp"));   
	        // 发送邮件协议名称  
	        props.setProperty("mail.transport.protocol", "smtp");  
	          
	        // 设置环境信息  
	        Session session = Session.getInstance(props);  
	          
	        // 创建邮件对象  
	        Message msg = new MimeMessage(session);  
	        String time =DateUtil.date2Str(new Date(), "yyyy-MM-dd");
	        msg.setSubject(env.getProperty("nsapi.mail.ordertitle")+"&"+time);  
	        
	    	// 设置发送人
			MimeMultipart partList = new MimeMultipart();
			// 写附件
			MimeBodyPart part2 = new MimeBodyPart();
			part2.attachFile(new File(dayReportName));
			part2.setFileName(MimeUtility.encodeText(dayReportName));
			// 把部件添加到集合中
//			partList.addBodyPart(part1);
			partList.addBodyPart(part2);
			msg.setContent(partList);
			
			 //设置自定义发件人昵称    
	        String nick="";    
	        try {    
	            nick=javax.mail.internet.MimeUtility.encodeText(env.getProperty("nsapi.mail.kaluli"));    
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();    
	        }
			
	        // 设置发件人 
//	        msg.setFrom(new InternetAddress(env.getProperty("nsapi.mail.sender")));  
	        msg.setFrom(new InternetAddress(nick+" <"+env.getProperty("nsapi.mail.sender")+">"));   
	          
	        Transport transport = session.getTransport();  
	        String emails=env.getProperty("nsapi.mail.orderdata");
	        String[] s =emails.split(",");
	        InternetAddress[] address = new InternetAddress[s.length];
	        for(int i=0;i<s.length;i++){
	        	address[i]=new InternetAddress(s[i]);
	        }
	        // 连接邮件服务器  (用户名密码)
	        transport.connect(env.getProperty("nsapi.mail.username"), env.getProperty("nsapi.mail.password"));
	        // 发送邮件  
	        transport.sendMessage(msg, address);
	        // 关闭连接  
	        transport.close();  
	
	}
	
	public static void main(String[] args) {
		String startTime="2016-11-30 21:17:26";
		String endTime="2016-12-20 16:43:56";
		String orderTime="2016-11-16 16:21:29";
		Date startDate = DateUtil.str2Date(startTime, "yyyy-MM-dd HH");
		Date endDate = DateUtil.str2Date(endTime, "yyyy-MM-dd HH");
		Date orderDate = DateUtil.str2Date(orderTime, "yyyy-MM-dd HH");
		int delivHour = DateUtil.intervalHourTest(startDate,orderDate);
		int delivHours = (int) ((startDate.getTime()-orderDate.getTime())/(1000*60*60));
		System.out.println(delivHour+"---"+delivHours);
		//收货时间
		BigDecimal deliv = new BigDecimal(delivHour);
		BigDecimal num = new BigDecimal(Double.valueOf("24"));
		BigDecimal delivery = deliv.divide(num,2,BigDecimal.ROUND_UP);
		int days = DateUtil.intervalHours(orderDate,endDate);
		System.out.println("days="+days);
		System.out.println("delivery="+delivery.toString());
		
		int expressHour = DateUtil.intervalHours(orderDate,endDate);
//		int expressHours = (int) ((endDate.getTime()-orderDate.getTime())/(1000*60*60));
//		System.out.println(expressHour+"---"+expressHours);
		BigDecimal expre = new BigDecimal(expressHour);
		BigDecimal express = expre.divide(num,2,BigDecimal.ROUND_UP);
		System.out.println(DateUtil.intervalDays(endDate, orderDate));
		System.out.println("express="+express.toString());
	}
}